package service

import (
	"exam12_23/config"
	"exam12_23/internal/api/request"
	"exam12_23/internal/models/dao"
	"gorm.io/gorm"
	"strconv"
)

func UserRegister(user *request.User) (uint, string) {
	users := dao.User{
		UserName: user.UserName,
		Password: user.Password,
	}
	err := config.DB.Model(&dao.User{}).Create(&users).Error
	if err != nil {
		return 0, "注册失败"
	}
	return users.ID, ""
}

func UserLogin(user *request.User) (uint, string) {
	var users *dao.User
	config.DB.Where("user_name=?", user.UserName).Limit(1).Find(&users)
	if users.ID == 0 {
		return 0, "登录失败"
	}
	return users.ID, ""
}

func UserList(list *request.UserList) []*dao.User {
	var user []*dao.User
	query := config.DB
	if list.UserName != "" {
		query.Model(&dao.User{}).Where("user_name like ?", "%"+list.UserName+"%").Scopes(Paginate(list.Page, list.PageSize)).Find(&user)
		return user
	}
	query.Model(&dao.User{}).Scopes(Paginate(list.Page, list.PageSize)).Find(&user)
	return user
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		page, _ = strconv.Atoi(strconv.Itoa(page))
		if page <= 0 {
			page = 1
		}

		pageSize, _ = strconv.Atoi(strconv.Itoa(pageSize))
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
